package com.scs.application.core.aliyun.sms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

@Slf4j
public class AliyunSmsHandler {

    @Autowired
    private AliyunSmsProperties aliyunSmsProperties;

    public void sendSms(String phones, String templateCode, Map<String, Object> params, String sign) {
        DefaultProfile profile = DefaultProfile.getProfile(aliyunSmsProperties.getRegion(), aliyunSmsProperties.getAccessKeyId(), aliyunSmsProperties.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(aliyunSmsProperties.getDomain());
        request.setVersion(aliyunSmsProperties.getVersion());
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", aliyunSmsProperties.getRegion());
        request.putQueryParameter("PhoneNumbers", phones);
        request.putQueryParameter("SignName", StringUtils.defaultIfBlank(sign, aliyunSmsProperties.getSign()));
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", params != null ? JSON.toJSONString(params) : "");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());

            JSONObject jsonObject = JSON.parseObject(response.getData());
            if ("OK".equalsIgnoreCase(jsonObject.getString("Code"))) {
                return;
            }
            throw new BusinessException("短信发送失败：" + jsonObject.getString("Message"));
        } catch (ClientException e) {
            throw new BusinessException("短信发送失败：" + e.getErrMsg(), e);
        }
    }

    /**
     * 发送短信
     *
     * @param phone        手机号，多个以 逗号 隔开，上限为1000个手机号
     * @param templateCode 模板代码
     * @param params       模板参数
     */
    public void sendSms(String phone, String templateCode, Map<String, Object> params) {
        sendSms(phone, templateCode, params, null);
    }
}
